package factorytest.iflytek.com.einkiflytekfactorytest.factorytestui;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.LruCache;

import com.android.server.roobo.RobotNVRomDataLocalJni;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import factorytest.iflytek.com.einkiflytekfactorytest.AgingTestActivity;
import factorytest.iflytek.com.einkiflytekfactorytest.R;
import factorytest.iflytek.com.einkiflytekfactorytest.RootApplication;
import factorytest.iflytek.com.einkiflytekfactorytest.config.EinkProperty;
import factorytest.iflytek.com.einkiflytekfactorytest.config.HtfyunBuildConfig;
import factorytest.iflytek.com.einkiflytekfactorytest.config.NVRomKeys;
import factorytest.iflytek.com.einkiflytekfactorytest.config.OTATestConfig;
import factorytest.iflytek.com.einkiflytekfactorytest.device.DeviceAttr;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.DebugLog;

public enum FactoryTestItemsEnum {
    first(1000, new String[]{NVRomKeys.KEY_FT_SCREEN, NVRomKeys.KEY_FT_LED, NVRomKeys.KEY_FT_HEADSET},
            true, R.string.ft_item_first, R.string.ft_item_first_en, FactoryFirstActivity.class),
    second(1001, new String[]{NVRomKeys.KEY_FT_FINGER_TP, NVRomKeys.KEY_FT_ELECTRIC_TP},
            true, R.string.ft_item_second, R.string.ft_item_second_en, FactorySecondActivity.class),
    third(1002, new String[]{NVRomKeys.KEY_FT_KEYS, NVRomKeys.KEY_FT_WAKEUP, NVRomKeys.KEY_FT_MIC},
            true, R.string.ft_item_third, R.string.ft_item_third_en, FactoryThirdActivity.class),
    bluetooth(1003, new String[]{NVRomKeys.KEY_FT_BLUETOOTH},
            true, R.string.ft_item_forth, R.string.ft_item_forth_en, FactoryBluetoothActivity.class),

    wifi(1004, new String[]{NVRomKeys.KEY_FT_WIFI},
            true, R.string.ft_item_wifi, R.string.ft_item_wifi_en, FactoryWifiListActivity.class),

    aging(1005, new String[]{NVRomKeys.KEY_FT_AGING},
            false, R.string.ft_item_aging, R.string.ft_item_aging_en, AgingTestActivity.class),

    battery(1006, new String[]{NVRomKeys.KEY_FT_BATTERY},
            false, R.string.ft_item_battery, R.string.ft_item_battery_en, null),

    pcba(1007, new String[]{NVRomKeys.KEY_FT_PCBA},
            false, R.string.ft_item_pcba, R.string.ft_item_pcba_en, null),

    sdcard(1008, new String[]{NVRomKeys.KEY_FT_SDCARD},
            false, R.string.ft_item_sdcard, R.string.ft_item_sdcard_en, null),

    ram(1009, new String[]{NVRomKeys.KEY_FT_RAM},
            false, R.string.ft_item_ram, R.string.ft_item_ram_en, null),

    rom(1010, new String[]{NVRomKeys.KEY_FT_ROM},
            false, R.string.ft_item_rom, R.string.ft_item_rom_en, null),

    ota(1011, new String[]{NVRomKeys.KEY_FT_OTA},
            false, R.string.ft_item_ota, R.string.ft_item_ota_en, null),
    ;
    private final int identify;
    private final String[] nvromKey;
    private final int nameResId;
    private final int nameEnResId;
    private final boolean keepTestAfterAging;
    private final Class<? extends Activity> ItemClass;
    private FactoryTestItemsEnum(int identify, String[] nvromKey, boolean testAfterAging,
                                 int nameResId, int nameEnResId, Class<? extends Activity> cls) {
        this.identify = identify;
        this.nvromKey = nvromKey;
        this.keepTestAfterAging = testAfterAging;
        this.nameResId = nameResId;
        this.nameEnResId = nameEnResId;
        ItemClass = cls;
    }

    public int getIdentify() {
        return identify;
    }

    public String[] getNVRomKey() {
        return nvromKey;
    }

    public String newNVRomKeyForAfterAging(String key) {
        return key + "_afterAging";
    }
    public String newNVRomKeyForLog(String key) {
        return key + "_log";
    }

    public boolean isKeepTestAfterAging() {
        return keepTestAfterAging;
    }
    public int getNameResId() {
        if (this == third && EinkProperty.isES7210Record()) {
            return R.string.ft_item_third_es7210;
        }
        return nameResId;
    }

    public int getNameEnResId() {
        return nameEnResId;
    }

    public Class<? extends Activity> getItemClass() {
        return ItemClass;
    }

    private final static String SHARED_PREFERENCES_NAME = "newfactoryTestItems";

    private static List<IFactoryTestItemSetListener> itemSetListenerList = new CopyOnWriteArrayList<>();


    public static void addItemSetListener(IFactoryTestItemSetListener itemSetListener) {
        if (!FactoryTestItemsEnum.itemSetListenerList.contains(itemSetListener)) {
            FactoryTestItemsEnum.itemSetListenerList.add(itemSetListener);
        }
    }

    public static void removeItemSetListener(IFactoryTestItemSetListener itemSetListener) {
        FactoryTestItemsEnum.itemSetListenerList.remove(itemSetListener);
    }

    public static void onItemSetListenerAction(String key, String result) {
        if (itemSetListenerList.isEmpty()) {
            return;
        }

        for (IFactoryTestItemSetListener listener : itemSetListenerList) {
            listener.onItemSet(key, result);
        }

    }

    public String getResult(Context context) {

        if (context == null) {
            context = RootApplication.getContext();
        }

        if (this == ota && !OTATestConfig.isEssentialForOTATest(context)) {
            return context.getResources().getString(R.string.test_result_pass);
        }

        String defResult = context.getResources().getString(R.string.test_result_unknown);

        String[] keys = getNVRomKey();
        if (keys == null || keys.length == 0) {
            return defResult;
        }

        return doGetResult(context, keys[0]);
    }

    public void setResult(Context context, String result) {

        String[] keys = getNVRomKey();
        if (keys == null || keys.length == 0) {
            return;
        }

        for (String key : keys) {
            doSetResult(context, key, result);
        }
    }

    public String getResultForAfterAging(Context context) {

        String defResult = "Pass";
        if (context != null) {
            defResult = context.getResources().getString(R.string.test_result_pass);
        }
        boolean keepTestAfterAging = isKeepTestAfterAging();
        if (!keepTestAfterAging) {
            return defResult;
        }

        String[] keys = getNVRomKey();
        if (keys == null || keys.length == 0) {
            return defResult;
        }

        return doGetResult(context, newNVRomKeyForAfterAging(keys[0]));

    }

    public void setResultForAfterAging(Context context, String result) {

        boolean keepTestAfterAging = isKeepTestAfterAging();
        if (!keepTestAfterAging) {
            return;
        }

        String[] keys = getNVRomKey();
        if (keys == null || keys.length == 0) {
            return;
        }

        for (String key : keys) {
            doSetResult(context, newNVRomKeyForAfterAging(key), result);
        }
    }

    public String getResultForLog(Context context) {

        StringBuilder sb = new StringBuilder("");
        String[] keys = getNVRomKey();
        if (keys == null || keys.length == 0) {
            return sb.toString();
        }

        String log = "";
        for (String key : keys) {
            log = doGetResult(context, newNVRomKeyForLog(key));
            sb.append(log + "\n");
        }

        return sb.toString();

    }

    public void setResultForLog(Context context, String log) {

        String[] keys = getNVRomKey();
        if (keys == null || keys.length == 0) {
            return;
        }

        for (String key : keys) {
            doSetResult(context, newNVRomKeyForLog(key), log);
        }

    }

    private String doGetResult(Context context, String key) {

        String defResult = "MA";
        if (context != null) {
            defResult = context.getResources().getString(R.string.test_result_unknown);
        }

        if (HtfyunBuildConfig.SAVE_TEST_RESULT_INTO_NVROM) {

            String result = nvromGetString(key);

            if (TextUtils.isEmpty(result)) {
                result = defResult;
            }

            return result;

        } else {

            if (context == null) {
                return "";
            }

            SharedPreferences sp = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);

            return sp.getString(key, defResult);
        }

    }

    private void doSetResult(Context context, String key, String result) {

        DebugLog.e("doSetResult key = " + key + ", result = " + result);

        if (HtfyunBuildConfig.SAVE_TEST_RESULT_INTO_NVROM) {

            nvromSetString(key, result);

        } else {

            if (context == null) {
                return;
            }

            SharedPreferences sp = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();

            editor.putString(key, result);
            editor.apply();
        }

        onItemSetListenerAction(key, result);
    }

    private LruCache<String, String> nvromCache = new LruCache<>(30);

    public String nvromGetString(String key) {
        String value = nvromCache.get(key);
        if (value == null) {
            value = RobotNVRomDataLocalJni.getInstance().getStringNVRom(key);
            nvromCache.put(key, value);
        }

        return value;
    }

    public void nvromSetString(String key, String value) {
        if (value == null) {
            return;
        }
        String savedValued = nvromGetString(key);
        if (savedValued != null && savedValued.equals(value)) {
            return;
        }
        nvromCache.put(key, value);
        RobotNVRomDataLocalJni.getInstance().setStringNVRom(key, value);
    }

    public boolean isPassed(Context context) {
        return isPassedWithResult(context, getResult(context));
    }

    public boolean isPassedForAfterAging(Context context) {
        return isPassedWithResult(context, getResultForAfterAging(context));
    }

    private boolean isPassedWithResult(Context context, String result) {

        if (this == sdcard && !DeviceAttr.getRunningDeviceAttr().hasTFCard()) {
            return true;
        }

        String pass = "Pass";
        if (context != null) {
            pass = context.getString(R.string.test_result_pass);
        }
        return !TextUtils.isEmpty(result) && !TextUtils.isEmpty(pass) && result.equalsIgnoreCase(pass);
    }


    /**
     * get item enum by id
     * @param id identify {@link #identify}
     * @return
     */
    public static FactoryTestItemsEnum getItemEnumByIdentify(final int id) {
        for (FactoryTestItemsEnum itemsEnum : values()) {
            if (itemsEnum.getIdentify() == id) {
                return itemsEnum;
            }
        }
        return null;
    }

}
